Program code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
int main(void)
{
int chosen = 0; // the lucky number
int guess = 0; // Stores a guess
int count = 3; // The meximum number of trie
int limit = 20; // Upper limit for pseudo-random values
char input;
do
{
srand(time(NULL)); // Use clock vlaue as starting seed
chosen = 1 + rand() % limit; // Random int 1 to limit
printf("\nThis is a guessing game.");
printf("\nI have chosen a number between 1 and 20"
" which you must guess.\n");
for( ; count > 0 ; --count)
{
printf("\nYou have %d tr%s left.", count,count == 1 ? "y" : "ies");
printf("\nEnter a guess: "); // Prompt for a guess
scanf("%d", &guess); // Read in a guess
// Check for a correct guess
if(guess == chosen)
{
printf("\nCongratulations. You guessed it!\n");
return 0; // End the program
}
else if(guess < 1 || guess > 20) // Check for an invalid guess
{
printf("I said the number is between 1 and 20.\n ");
}
else
{
printf("Sorry, %d is wrong. My number is %s than that.\n", guess, chosen > guess ? "greater" : "less");
}
}
printf("\nYou have had three tries and failed. The number was %ld\n", chosen);
printf("Do you want to play another game? (Press Y to replay)\n");
scanf(" %c", &input);
} while(toupper(input) == 'Y'); // if 'Y' is pressed loop program
return 0;
}
Please, only the final two printf() statements (functions) are executing and scanf() following a failed 3 error response, am I missing a bracket somewhere which would make the do while loop loop the entire program successfully on a "y" or "Y" response for the scanf() function:
Code:
scanf(" %c", &input);